package com.aaron.kjviewutils;

import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.TextView;

import com.aaron.kjviewutils.eventBus.EventBusMsg;
import com.aaron.kjviewutils.glide.GlideCircleTransform;
import com.aaron.kjviewutils.retrofit.RetrofitUtil;
import com.aaron.kjviewutils.retrofit.service.WeatherService;
import com.aaron.kjviewutils.weather.WeatherSettingBean;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.github.ybq.android.spinkit.Style;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 作者：Aaron on 2017/2/14 17:33
 * 邮箱：kaijin.fang@edianniu.com
 */
public class SettingActivity extends BaseActivity {

    @Bind(R.id.settingToolBar)
    Toolbar settingToolBar;
    @Bind(R.id.barTitle)
    TextView barTitle;
    @Bind(R.id.leftBarIcon)
    ImageView leftBarIcon;
    @Bind(R.id.modifyPswIcon)
    ImageView modifyPswIcon;
    @Bind(R.id.settingCityIcon)
    ImageView settingCityIcon;
    @Bind(R.id.settingUpgradeIcon)
    ImageView settingUpgradeIcon;
    @Bind(R.id.logonIcon)
    ImageView logonIcon;
    @Bind(R.id.mobSettingIcon)
    ImageView mobSettingIcon;
    @Bind(R.id.logonLabel)
    TextView logonLabel;

    private WeatherService weatherService;
    private Call<ResponseBody> call;
    private List<WeatherSettingBean> weatherCitys;
    private OptionsPickerView options;
    private String cityT;
    private String areaT;


    @OnClick(R.id.leftBarIcon)
    void leftBarIconClick()
    {
        /*if(null!=menu)
        {
            menu.showMenu(true);
        }*/
        closeSelf(SettingActivity.this);
    }

    @OnClick(R.id.mobSettingL)
    void mobSettingL()
    {

    }

    @OnClick(R.id.modifyPswL)
    void modifyPswL()
    {

    }

    @OnClick(R.id.settingCityL)
    void settingCityL()
    {
        /*if(null!=cityPicker)
        {
            cityPicker.show();
            cityPicker.setOnCitySelectListener(new OnSimpleCitySelectListener() {
                @Override
                public void onCitySelect(String prov, String city, String area) {
                    if(!TextUtils.isEmpty(city))
                    {
                        saveCitys(prov, city);
                    }
                    else
                    {
                        saveCitys(prov, area);
                    }
                }

                @Override
                public void onCitySelect(String str) {
                    Toast.makeText(SettingActivity.this, "你选择的地址：" + str, Toast.LENGTH_SHORT).show();
                }
            });
        }*/
        eventBus.post(new EventBusMsg(EventBusMsg.EventBusType.SETTING_CITYS));
    }

    @OnClick(R.id.settingUpgradeL)
    void settingUpgradeL()
    {

    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 80)
    public void onEvent(EventBusMsg msg)
    {
        switch (msg.getType())
        {
            case SETTING_CITYS:
            {
                mHandler.post(runnableLoadData);
            }
            break;
            case SETTING_CITYS_LOAD:
            {
                ArrayList<String> provinces = new ArrayList<String>();
                final ArrayList<ArrayList<String>> citys = new ArrayList<ArrayList<String>>();
                final ArrayList<ArrayList<ArrayList<String>>> areas = new ArrayList<ArrayList<ArrayList<String>>>();
                if(null!=weatherCitys&&!weatherCitys.isEmpty())
                {
                    for(WeatherSettingBean weatherSetting:weatherCitys)
                    {
                        List<WeatherSettingBean.CitySettingBean> citySettings = weatherSetting.city;
                        if(null!=citySettings&&!citySettings.isEmpty())
                        {
                            ArrayList<String> citysItem = new ArrayList<String>();
                            ArrayList<ArrayList<String>> areasItem = new ArrayList<ArrayList<String>>();
                            for(WeatherSettingBean.CitySettingBean citySetting:citySettings)
                            {
                                List<WeatherSettingBean.CitySettingBean.DistrictBean> districtSettings = citySetting.district;
                                if(null!=districtSettings&&!districtSettings.isEmpty())
                                {
                                    citysItem.add(citySetting.city);
                                    ArrayList<String> areasItemInner = new ArrayList<String>();
                                    for(WeatherSettingBean.CitySettingBean.DistrictBean district:districtSettings)
                                    {
                                        areasItemInner.add(district.district);
                                    }
                                    areasItem.add(areasItemInner);
                                }
                            }
                            areas.add(areasItem);
                            citys.add(citysItem);
                        }
                        provinces.add(weatherSetting.province);
                    }
                    if(null==options)
                    {
                        options = new OptionsPickerView(this);
                    }
                    //封装数据
                    options.setPicker(provinces, citys, areas, true);
                    options.setTitle("设置城市信息");
                    options.setCyclic(false, false, false);
                    options.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int i, int i1, int i2) {
                            cityT = citys.get(i).get(i1);
                            areaT = areas.get(i).get(i1).get(i2);
                            saveCitys(cityT, areaT);
                        }
                    });
                    options.show();
                }
            }
            break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.layout_setting);
        ButterKnife.bind(this);
        initTitle();
        initContent();
    }

    Runnable runnableLoadData = new Runnable() {
        @Override
        public void run() {
            if(null!=progress)
            {
                progress.showProgress(Style.WAVE);
                progress.showAtLocation(settingToolBar, Gravity.CENTER, 0, 0);
            }
            if(null==retrofit)
            {
                retrofit = RetrofitUtil.obtainRetrofit();
            }
            weatherService = retrofit.create(WeatherService.class);
            call = weatherService.obtainCitys();
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    call.cancel();
                    if (null != progress) {
                        progress.dismissView();
                    }
                    try {
                        String source = response.body().string();
                        if (TextUtils.isEmpty(source)) {
                            showMsg("获取城市信息失败");
                        } else {
                            JSONObject object = new JSONObject(source);
                            Gson gson = new Gson();
                            if ("200".equals(object.getString("retCode"))) {
                                weatherCitys = new ArrayList<WeatherSettingBean>();
                                JsonParser parser = new JsonParser();
                                JsonObject json01 = parser.parse(source).getAsJsonObject();
                                JsonArray json02 = json01.getAsJsonArray("result");
                                int size = json02.size();
                                for (int i = 0; i < size; i++) {
                                    JsonObject jsonObject = json02.get(i).getAsJsonObject();
                                    WeatherSettingBean weatherSetting = new WeatherSettingBean();
                                    weatherSetting =gson.fromJson(jsonObject, new TypeToken<WeatherSettingBean>() {
                                    }.getType());
                                    weatherCitys.add(weatherSetting);
                                }
                                eventBus.post(new EventBusMsg(EventBusMsg.EventBusType.SETTING_CITYS_LOAD));
                            } else {
                                showMsg(object.getString("msg"));
                            }
                        }
                    } catch (IOException e) {
                        showMsg("获取城市信息失败");
                    } catch (JSONException e) {
                        showMsg("获取城市信息失败");
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    call.cancel();
                    if (null != progress) {
                        progress.dismissView();
                    }
                    showMsg("加载城市数据失败");
                }
            });
        }
    };

    private void initContent()
    {
        Glide.with(SettingActivity.this).load("http://www.mob.com/mob/images/apiyun/index/B_49.png").transform(new GlideCircleTransform(SettingActivity.this)).animate(android.R.anim.slide_in_left).placeholder(R.mipmap.ic_launcher).into(mobSettingIcon);
        Glide.with(SettingActivity.this).load("http://g.hiphotos.baidu.com/exp/w=200/sign=ccca5bb9ce95d143da76e32343f18296/8601a18b87d6277f104285822e381f30e924fc3c.jpg").transform(new GlideCircleTransform(SettingActivity.this)).animate(android.R.anim.slide_in_left).placeholder(R.mipmap.ic_launcher).into(modifyPswIcon);
        Glide.with(SettingActivity.this).load("http://u5.mm-img.mmarket.com/rs/res2/21/2014/11/01/a469/511/39511469/logo1140x1404842901963_src.jpg").transform(new GlideCircleTransform(SettingActivity.this)).animate(android.R.anim.slide_in_left).placeholder(R.mipmap.ic_launcher).into(settingCityIcon);
        Glide.with(SettingActivity.this).load("http://src.onlinedown.net/new_img/apk_logo/2016/0119/257251_1453172278_3986.png").transform(new GlideCircleTransform(SettingActivity.this)).animate(android.R.anim.slide_in_left).placeholder(R.mipmap.ic_launcher).into(settingUpgradeIcon);
        Glide.with(SettingActivity.this).load("http://image.coolapk.com/apk_logo/2012/1009/12202_1349785874_6494.png").transform(new GlideCircleTransform(SettingActivity.this)).animate(android.R.anim.slide_in_left).placeholder(R.mipmap.ic_launcher).into(logonIcon);
        logonLabel.setText("安全登出");
    }

    private void initTitle()
    {
        settingToolBar.setTitle("");
        barTitle.setText("系统设置");
        loadBackground(leftBarIcon, resources.getDrawable(R.mipmap.back));
        settingToolBar.setNavigationIcon(null);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN)
        {
            //关闭
            closeSelf(SettingActivity.this);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null!=mHandler)
        {
            mHandler.removeCallbacks(runnableLoadData);
        }
        if(null!=progress) {
            progress.dismissView();
        }
        if(null!=call) {
            call.cancel();
        }
        if(null!=options&&options.isShowing())
        {
            options.dismiss();
        }
        ButterKnife.unbind(this);
    }
}
